import { create } from 'zustand'
import { subscribeWithSelector, persist } from 'zustand/middleware'
import { PanelState, ViewerType, SliceOrientation } from '@/types/image'

// 导航历史接口
interface NavigationHistory {
    path: string
    timestamp: number
    state?: Record<string, unknown>
}

// 面包屑项接口
interface BreadcrumbItem {
    label: string
    path: string
    isActive: boolean
}

// 通知接口
interface Notification {
    id: string
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message: string
    duration?: number
    timestamp: number
}

// 模态框状态接口
interface ModalState {
    isOpen: boolean
    type: string | null
    data?: Record<string, unknown>
}

// 侧边栏状态接口
interface SidebarState {
    isCollapsed: boolean
    activeTab: string | null
    width: number
}

// 工具栏状态接口
interface ToolbarState {
    activeTool: string | null
    toolSettings: Record<string, unknown>
}

// 扩展的面板状态接口
interface ExtendedPanelState extends PanelState {
    currentSlice?: number
    maxSlice?: number
    isVisible: boolean
    isSynchronized: boolean
}

export interface UIStore {
    // 选择状态
    selectedDataset: string | null
    selectedTask: string | null
    selectedImage: string | null
    viewerType: ViewerType | null

    // 面板状态
    panelStates: {
        axial: ExtendedPanelState
        sagittal: ExtendedPanelState
        coronal: ExtendedPanelState
        main: ExtendedPanelState
        aux: ExtendedPanelState
    }

    // 同步设置
    synchronization: {
        enabled: boolean
        syncZoom: boolean
        syncPan: boolean
        syncWindowLevel: boolean
        syncSlice: boolean
    }

    // 界面布局
    layout: {
        sidebar: SidebarState
        toolbar: ToolbarState
        fullscreen: boolean
        theme: 'light' | 'dark' | 'auto'
    }

    // 导航状态
    navigation: {
        currentPath: string
        history: NavigationHistory[]
        breadcrumbs: BreadcrumbItem[]
        canGoBack: boolean
        canGoForward: boolean
    }

    // 通知系统
    notifications: Notification[]

    // 模态框状态
    modals: Record<string, ModalState>

    // 加载状态
    loading: {
        global: boolean
        components: Record<string, boolean>
    }

    // 用户偏好设置
    preferences: {
        autoSave: boolean
        showTooltips: boolean
        animationsEnabled: boolean
        defaultWindowLevel: [number, number]
        defaultZoom: number
        language: string
    }

    // Actions - 选择操作
    setSelectedDataset: (datasetId: string | null) => void
    setSelectedTask: (taskId: string | null) => void
    setSelectedImage: (imageId: string | null) => void
    setViewerType: (type: ViewerType | null) => void

    // Actions - 面板操作
    updatePanelState: (panel: keyof UIStore['panelStates'], state: Partial<ExtendedPanelState>) => void
    resetPanelState: (panel: keyof UIStore['panelStates']) => void
    resetAllPanels: () => void
    synchronizePanels: (sourcePanel: keyof UIStore['panelStates'], changes: Partial<ExtendedPanelState>) => void

    // Actions - 同步设置
    updateSynchronization: (settings: Partial<UIStore['synchronization']>) => void
    toggleSynchronization: () => void

    // Actions - 布局操作
    updateLayout: (layout: Partial<UIStore['layout']>) => void
    toggleSidebar: () => void
    setSidebarTab: (tab: string | null) => void
    setActiveTool: (tool: string | null) => void
    toggleFullscreen: () => void
    setTheme: (theme: 'light' | 'dark' | 'auto') => void

    // Actions - 导航操作
    navigate: (path: string, state?: Record<string, unknown>) => void
    goBack: () => void
    goForward: () => void
    updateBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => void

    // Actions - 通知操作
    addNotification: (notification: Omit<Notification, 'id' | 'timestamp'>) => void
    removeNotification: (id: string) => void
    clearNotifications: () => void

    // Actions - 模态框操作
    openModal: (type: string, data?: Record<string, unknown>) => void
    closeModal: (type: string) => void
    closeAllModals: () => void

    // Actions - 加载状态操作
    setGlobalLoading: (loading: boolean) => void
    setComponentLoading: (component: string, loading: boolean) => void

    // Actions - 偏好设置操作
    updatePreferences: (preferences: Partial<UIStore['preferences']>) => void
    resetPreferences: () => void
}

// 默认面板状态
const createDefaultPanelState = (): ExtendedPanelState => ({
    zoom: 1,
    pan: [0, 0],
    windowLevel: [400, 1600],
    rotation: 0,
    currentSlice: 0,
    maxSlice: 0,
    isVisible: true,
    isSynchronized: true
})

// 默认偏好设置
const defaultPreferences = {
    autoSave: true,
    showTooltips: true,
    animationsEnabled: true,
    defaultWindowLevel: [400, 1600] as [number, number],
    defaultZoom: 1,
    language: 'zh-CN'
}

// 生成唯一ID
const generateId = (): string => {
    return `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
}

export const useUIStore = create<UIStore>()(
    persist(
        subscribeWithSelector((set, get) => ({
            // 初始状态
            selectedDataset: null,
            selectedTask: null,
            selectedImage: null,
            viewerType: null,

            panelStates: {
                axial: createDefaultPanelState(),
                sagittal: createDefaultPanelState(),
                coronal: createDefaultPanelState(),
                main: createDefaultPanelState(),
                aux: createDefaultPanelState()
            },

            synchronization: {
                enabled: true,
                syncZoom: true,
                syncPan: true,
                syncWindowLevel: true,
                syncSlice: true
            },

            layout: {
                sidebar: {
                    isCollapsed: false,
                    activeTab: null,
                    width: 300
                },
                toolbar: {
                    activeTool: null,
                    toolSettings: {}
                },
                fullscreen: false,
                theme: 'light'
            },

            navigation: {
                currentPath: '/',
                history: [],
                breadcrumbs: [],
                canGoBack: false,
                canGoForward: false
            },

            notifications: [],
            modals: {},

            loading: {
                global: false,
                components: {}
            },

            preferences: { ...defaultPreferences },

            // Actions - 选择操作
            setSelectedDataset: (datasetId: string | null) => {
                set({ selectedDataset: datasetId })
            },

            setSelectedTask: (taskId: string | null) => {
                set({ selectedTask: taskId })
            },

            setSelectedImage: (imageId: string | null) => {
                set({ selectedImage: imageId })
            },

            setViewerType: (type: ViewerType | null) => {
                set({ viewerType: type })
            },

            // Actions - 面板操作
            updatePanelState: (panel: keyof UIStore['panelStates'], state: Partial<ExtendedPanelState>) => {
                const store = get()
                const currentState = store.panelStates[panel]
                const newState = { ...currentState, ...state }

                set(prevState => ({
                    panelStates: {
                        ...prevState.panelStates,
                        [panel]: newState
                    }
                }))

                // 如果启用了同步，同步到其他面板
                if (store.synchronization.enabled && newState.isSynchronized) {
                    store.synchronizePanels(panel, state)
                }
            },

            resetPanelState: (panel: keyof UIStore['panelStates']) => {
                set(state => ({
                    panelStates: {
                        ...state.panelStates,
                        [panel]: createDefaultPanelState()
                    }
                }))
            },

            resetAllPanels: () => {
                set({
                    panelStates: {
                        axial: createDefaultPanelState(),
                        sagittal: createDefaultPanelState(),
                        coronal: createDefaultPanelState(),
                        main: createDefaultPanelState(),
                        aux: createDefaultPanelState()
                    }
                })
            },

            synchronizePanels: (sourcePanel: keyof UIStore['panelStates'], changes: Partial<ExtendedPanelState>) => {
                const store = get()
                const { synchronization } = store

                if (!synchronization.enabled) return

                const syncChanges: Partial<ExtendedPanelState> = {}

                if (synchronization.syncZoom && changes.zoom !== undefined) {
                    syncChanges.zoom = changes.zoom
                }
                if (synchronization.syncPan && changes.pan !== undefined) {
                    syncChanges.pan = changes.pan
                }
                if (synchronization.syncWindowLevel && changes.windowLevel !== undefined) {
                    syncChanges.windowLevel = changes.windowLevel
                }
                if (synchronization.syncSlice && changes.currentSlice !== undefined) {
                    syncChanges.currentSlice = changes.currentSlice
                }

                if (Object.keys(syncChanges).length === 0) return

                const updatedPanelStates = { ...store.panelStates }

                Object.keys(updatedPanelStates).forEach(panelKey => {
                    if (panelKey !== sourcePanel) {
                        const panel = panelKey as keyof UIStore['panelStates']
                        if (updatedPanelStates[panel].isSynchronized) {
                            updatedPanelStates[panel] = {
                                ...updatedPanelStates[panel],
                                ...syncChanges
                            }
                        }
                    }
                })

                set({ panelStates: updatedPanelStates })
            },

            // Actions - 同步设置
            updateSynchronization: (settings: Partial<UIStore['synchronization']>) => {
                set(state => ({
                    synchronization: { ...state.synchronization, ...settings }
                }))
            },

            toggleSynchronization: () => {
                set(state => ({
                    synchronization: {
                        ...state.synchronization,
                        enabled: !state.synchronization.enabled
                    }
                }))
            },

            // Actions - 布局操作
            updateLayout: (layout: Partial<UIStore['layout']>) => {
                set(state => ({
                    layout: { ...state.layout, ...layout }
                }))
            },

            toggleSidebar: () => {
                set(state => ({
                    layout: {
                        ...state.layout,
                        sidebar: {
                            ...state.layout.sidebar,
                            isCollapsed: !state.layout.sidebar.isCollapsed
                        }
                    }
                }))
            },

            setSidebarTab: (tab: string | null) => {
                set(state => ({
                    layout: {
                        ...state.layout,
                        sidebar: {
                            ...state.layout.sidebar,
                            activeTab: tab
                        }
                    }
                }))
            },

            setActiveTool: (tool: string | null) => {
                set(state => ({
                    layout: {
                        ...state.layout,
                        toolbar: {
                            ...state.layout.toolbar,
                            activeTool: tool
                        }
                    }
                }))
            },

            toggleFullscreen: () => {
                set(state => ({
                    layout: {
                        ...state.layout,
                        fullscreen: !state.layout.fullscreen
                    }
                }))
            },

            setTheme: (theme: 'light' | 'dark' | 'auto') => {
                set(state => ({
                    layout: {
                        ...state.layout,
                        theme
                    }
                }))
            },

            // Actions - 导航操作
            navigate: (path: string, state?: Record<string, unknown>) => {
                const store = get()
                const historyEntry: NavigationHistory = {
                    path: store.navigation.currentPath,
                    timestamp: Date.now(),
                    state
                }

                set(prevState => ({
                    navigation: {
                        ...prevState.navigation,
                        currentPath: path,
                        history: [...prevState.navigation.history, historyEntry],
                        canGoBack: true
                    }
                }))
            },

            goBack: () => {
                const store = get()
                const { history } = store.navigation

                if (history.length > 0) {
                    const previousEntry = history[history.length - 1]
                    const newHistory = history.slice(0, -1)

                    set({
                        navigation: {
                            ...store.navigation,
                            currentPath: previousEntry.path,
                            history: newHistory,
                            canGoBack: newHistory.length > 0,
                            canGoForward: true
                        }
                    })
                }
            },

            goForward: () => {
                // 实现前进逻辑（需要额外的前进历史栈）
                console.log('Forward navigation not implemented yet')
            },

            updateBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => {
                set(state => ({
                    navigation: {
                        ...state.navigation,
                        breadcrumbs
                    }
                }))
            },

            // Actions - 通知操作
            addNotification: (notification: Omit<Notification, 'id' | 'timestamp'>) => {
                const newNotification: Notification = {
                    ...notification,
                    id: generateId(),
                    timestamp: Date.now()
                }

                set(state => ({
                    notifications: [...state.notifications, newNotification]
                }))

                // 自动移除通知
                if (notification.duration !== 0) {
                    const duration = notification.duration || 5000
                    setTimeout(() => {
                        get().removeNotification(newNotification.id)
                    }, duration)
                }
            },

            removeNotification: (id: string) => {
                set(state => ({
                    notifications: state.notifications.filter(n => n.id !== id)
                }))
            },

            clearNotifications: () => {
                set({ notifications: [] })
            },

            // Actions - 模态框操作
            openModal: (type: string, data?: Record<string, unknown>) => {
                set(state => ({
                    modals: {
                        ...state.modals,
                        [type]: {
                            isOpen: true,
                            type,
                            data
                        }
                    }
                }))
            },

            closeModal: (type: string) => {
                set(state => ({
                    modals: {
                        ...state.modals,
                        [type]: {
                            isOpen: false,
                            type: null,
                            data: undefined
                        }
                    }
                }))
            },

            closeAllModals: () => {
                const store = get()
                const closedModals: Record<string, ModalState> = {}

                Object.keys(store.modals).forEach(key => {
                    closedModals[key] = {
                        isOpen: false,
                        type: null,
                        data: undefined
                    }
                })

                set({ modals: closedModals })
            },

            // Actions - 加载状态操作
            setGlobalLoading: (loading: boolean) => {
                set(state => ({
                    loading: {
                        ...state.loading,
                        global: loading
                    }
                }))
            },

            setComponentLoading: (component: string, loading: boolean) => {
                set(state => ({
                    loading: {
                        ...state.loading,
                        components: {
                            ...state.loading.components,
                            [component]: loading
                        }
                    }
                }))
            },

            // Actions - 偏好设置操作
            updatePreferences: (preferences: Partial<UIStore['preferences']>) => {
                set(state => ({
                    preferences: { ...state.preferences, ...preferences }
                }))
            },

            resetPreferences: () => {
                set({ preferences: { ...defaultPreferences } })
            }
        })),
        {
            name: 'ui-store',
            partialize: (state) => ({
                // 只持久化用户偏好和布局设置
                preferences: state.preferences,
                layout: {
                    sidebar: state.layout.sidebar,
                    theme: state.layout.theme
                },
                synchronization: state.synchronization
            })
        }
    )
)